const jwt = require('jsonwebtoken')
const AdminUser = require('../models/AdminUser')
const assert = require('http-assert')

module.exports = options => {
  return async (req, res, next) => {
    // 校验用户是否登陆
    const token = String(req.headers.authorization || '').split(' ').pop()
    assert(token, 401, '请提供JWT Token')
    const tokenData = jwt.verify(token, req.app.get('secret'))
    const id = tokenData.id
    assert(id, 401, '无效的JWT Token')
    req.user = await AdminUser.findById(id)
    assert(req.user, 401, '请先登录')
    await next()
  }
}
